Page({
  /**
   * 页面的初始数据
   */
  data: {
    content: '',      // 日记内容
    mood: 'positive', // 默认情绪
    imagePath: '',    // 图片路径
    isEditing: false, // 是否为编辑模式
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.id) {
      this.setData({ isEditing: true });
      const diaries = wx.getStorageSync('diaries') || {};
      const diary = diaries[options.id];
      if (diary) {
        this.setData({
          content: diary.content,
          mood: diary.mood || 'positive',
          imagePath: diary.imagePath || ''
        });
      }
    }
  },

  /**
   * 处理日记内容输入
   */
  onContentInput(e) {
    this.setData({ content: e.detail.value });
  },

  /**
   * 切换情绪
   */
  toggleMood(e) {
    const mood = e.currentTarget.dataset.mood; // 获取按钮传递的情绪值
    this.setData({ mood });
    wx.showToast({
      title: `已切换到${mood}情绪`,
      icon: 'none',
      duration: 1500
    });
  },

  /**
   * 选择图片
   */
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({ imagePath: res.tempFilePaths[0] });
      },
      fail: (err) => {
        console.error('选择图片失败', err);
      }
    });
  },

  /**
   * 保存日记
   */
  saveDiary() {
    if (!this.data.content) {
      wx.showToast({
        title: '内容不能为空',
        icon: 'none',
        duration: 1500
      });
      return;
    }

    const diaries = wx.getStorageSync('diaries') || {};
    const diary = {
      content: this.data.content,
      mood: this.data.mood,
      date: new Date().toISOString(),
      imagePath: this.data.imagePath
    };

    const id = this.data.isEditing ? options.id : new Date().toISOString(); // 如果是编辑模式，保留原ID
    diaries[id] = diary;

    wx.setStorageSync('diaries', diaries);

    wx.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 1500
    });

    setTimeout(() => {
      wx.navigateBack();
    }, 1500);
  }
});
